package boot.spring.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.HistoryService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import boot.spring.pagemodel.MSG;
import boot.spring.util.Jump2TargetFlowNodeCommand;
import io.swagger.annotations.Api;

@Api(value = "测试流程接口")
@Controller
@RequestMapping("utils")
public class UtilsController {
	
	@Autowired
	TaskService taskservice;
	@Autowired
	HistoryService histiryservice;
	
	@RequestMapping(value="/getTargetNodeId",method=RequestMethod.POST)
	@ResponseBody
	public MSG getTargetNodeId(@RequestParam("taskid") String taskid, HttpServletRequest req) {
		String msg = "fail"; 
		if(StringUtils.isNotEmpty(taskid)) {
			String targetNodeKey = getTargetNodeKey(taskid);
			if(StringUtils.isNotEmpty(targetNodeKey)) {
				ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
				ManagementService managementService = engine.getManagementService();
				managementService.executeCommand(new Jump2TargetFlowNodeCommand(taskid, targetNodeKey));
				//跳转至上个节点成功
				System.out.println("跳转至上个节点成功");
				msg = "success";
			}
		}else {
			System.out.println("参数taskId是空的");
			msg = "fail";
		}
		return new MSG(msg);
	}
	private String getTargetNodeKey(String taskId) {
		String targetNodeKey = null;
		Task task = taskservice.createTaskQuery()//
                .taskId(taskId)//使用任务ID查询
                .singleResult();
		if (task == null) {
	           // throw new ServiceException("任务不存在");
	            System.out.println("任务不存在");
	        }
		 String processInstanceId = task.getProcessInstanceId();
	        List<HistoricTaskInstance> list = histiryservice//与历史数据（历史表）相关的service
	                .createHistoricTaskInstanceQuery()//创建历史任务实例查询
	                .processInstanceId(processInstanceId)
	                .list();
	        //logger.info("上一节点任务ID：{}" + list.get(list.size() - 2).getId());
	        if(null != list && list.size()>1) {
	        	//不超过2个节点记录，Key也设置为空
	        	System.out.println("上一节点任务ID：{}" + list.get(list.size() - 2).getId());
	            System.out.println("上一节点任务Key：{}" + list.get(list.size() - 2).getTaskDefinitionKey());
	            targetNodeKey = list.get(list.size() - 2).getTaskDefinitionKey();
	        }
	        return targetNodeKey;
	}

}
